package com.fesine.batch.service.impl;

import com.fesine.batch.dao.IDaoService;
import com.fesine.batch.model.BatchSchedulePo;
import com.fesine.batch.service.BatchScheduleService;
import com.fesine.batch.service.BatchSchedulerBrokerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @description: 类描述
 * @author: Fesine
 * @createTime:2017/2/27 21:56
 * @update:修改内容
 * @author: Fesine
 * @updateTime:2017/2/27 21:56
 */
@Service("batchScheduleService")
public class BatchScheduleServiceImpl implements BatchScheduleService {
    @Resource
    private IDaoService daoService;
    @Autowired
    private BatchSchedulerBrokerService batchSchedulerBroker;

    @Override
    public List<BatchSchedulePo> listSchedule(BatchSchedulePo batchSchedulePo) {
        return daoService.selectList(batchSchedulePo);
    }

    @Override
    public List<BatchSchedulePo> listPage(BatchSchedulePo batchSchedulePo, int pageNum, int
            pageSize) {
        return daoService.selectList(batchSchedulePo, pageNum, pageSize);
    }

    @Override
    public List<BatchSchedulePo> listLike(BatchSchedulePo batchSchedulePo, int pageNum, int
            pageSize) {
        String mapper = BatchSchedulePo.class.getName() + ".selectLikeGroupId";
        return daoService.selectList(mapper, batchSchedulePo, pageNum, pageSize);
    }

    @Override
    public long count(BatchSchedulePo batchSchedulePo) {
        return daoService.count(batchSchedulePo);
    }

    @Override
    public int add(BatchSchedulePo batchSchedulePo) {
        int i = daoService.insert(batchSchedulePo);
        if (batchSchedulePo.getStatus() == 1) {
            batchSchedulerBroker.schedule(batchSchedulePo.getGroupId(), batchSchedulePo
                    .getStartTime());
        }
        return i;
    }

    @Override
    public BatchSchedulePo get(BatchSchedulePo batchSchedulePo) {
        return daoService.selectOne(batchSchedulePo);
    }

    @Override
    public int update(BatchSchedulePo batchSchedulePo) {
        if (batchSchedulePo.getStatus() == 1) {
            batchSchedulerBroker.schedule(batchSchedulePo.getGroupId(), batchSchedulePo
                    .getStartTime());
        } else {
            batchSchedulerBroker.unschedule(batchSchedulePo.getGroupId());
        }
        return daoService.update(batchSchedulePo);
    }

    @Override
    public int delete(BatchSchedulePo batchSchedulePo) {
        batchSchedulePo = daoService.selectOne(batchSchedulePo);
        //如果是新增返回null
        if (batchSchedulePo == null) {
            return 0;
        }
        //启用状态，需要先删除定时器任务
        if (batchSchedulePo.getStatus() == 1) {
            batchSchedulerBroker.unschedule(batchSchedulePo.getGroupId());
        }
        return daoService.delete(batchSchedulePo);
    }
}
